package lrscp.lib;

import lrscp.lib.KeyboardEvent.GlobalKeyboardEventListener;
import lrscp.lib.MouseEvent.GlobalMouseEventListener;

public class GlobalEventListener {
	PoolHook pt;

	public GlobalEventListener() {
		pt = new PoolHook(this);
		pt.start();
	}

	protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList();

	public void addKeyboardEventListener(GlobalKeyboardEventListener listener) {
		listenerList.add(GlobalKeyboardEventListener.class, listener);
	}

	public void removeKeyboardEventListener(GlobalKeyboardEventListener listener) {
		listenerList.remove(GlobalKeyboardEventListener.class, listener);
	}

	public void addMouseEventListener(GlobalMouseEventListener listener) {
		listenerList.add(GlobalMouseEventListener.class, listener);
	}

	public void removeMouseEventListener(GlobalMouseEventListener listener) {
		listenerList.remove(GlobalMouseEventListener.class, listener);
	}

	void keyPressed(KeyboardEvent event) {
		Object[] listeners = listenerList.getListenerList();
		for (int i = 0; i < listeners.length; i += 2) {
			if (listeners[i] == GlobalKeyboardEventListener.class) {
				((GlobalKeyboardEventListener) listeners[i + 1]).onGlobalKeyEvent(event);
			}
		}
	}

	void mouseMoved(MouseEvent event) {
		Object[] listeners = listenerList.getListenerList();
		for (int i = 0; i < listeners.length; i += 2) {
			if (listeners[i] == GlobalMouseEventListener.class) {
				((GlobalMouseEventListener) listeners[i + 1]).onGlobalMouseEvent(event);
			}
		}
	}
}

class PoolHook extends Thread {
	SysHook hook;
	GlobalEventListener g_gl;

	PoolHook(GlobalEventListener gl) {
		g_gl = gl;
	}

	public void run() {
		hook = new SysHook();
		hook.registerHook(g_gl);
	}
}

class SysHook {
	static {
		System.loadLibrary("SysHook");
	}

	void processKey(boolean ts, int vk, GlobalEventListener gl) {
		KeyboardEvent event = new KeyboardEvent(this, ts, vk, false, false);
		gl.keyPressed(event);
	}

	void mouseMoved(int cord_x, int cord_y, GlobalEventListener gl) {
		MouseEvent event = new MouseEvent(this, cord_x, cord_y);
		gl.mouseMoved(event);
	}

	native void registerHook(GlobalEventListener gl);

	native void unRegisterHook();
}


